package com.vanka.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.vanka.entity.account.*;
import com.vanka.mapper.account.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * @author VanKa qq:2395073039
 * @date 2021/7/26 9:09
 */
@Component
public class LoginService implements UserDetailsService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private RoleMapper roleMapper;
    @Autowired
    private RolePermissionMapper rolePermissionMapper;
    @Autowired
    private PermissionMapper permissionMapper;
    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        // 1.根据用户名称查询到user用户
        User u = userMapper.selectOne(new QueryWrapper<User>().eq("phone",s));
        if (u == null) {
            return null;
        }
        // 2.查询该用户对应的角色
        Role role = roleMapper.selectById(u.getType());
        if (role == null){
            return null;
        }
        UserEntity userDetails = new UserEntity();
        userDetails.setUser(u);
        // 3.查询该角色关联权限
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(new QueryWrapper<RolePermission>().eq("roleId", role.getId()));
       if (rolePermissions != null){
           ArrayList<GrantedAuthority> grantedAuthorities = new ArrayList<>();
           rolePermissions.forEach((a) -> {
               // 获取权限并添加
               Permission p = permissionMapper.selectById(a.getPermissionId());
               if (p != null){
                   grantedAuthorities.add(new SimpleGrantedAuthority(p.getTag()));
               }
           });

           // 设置权限
           userDetails.setAuthorities(grantedAuthorities);
       }

        return userDetails;
    }
}
